import uuid

from util import GetConn, GetMd5


def Login(data):
    '''
    用户登录
    :param data: 用户数据
    :return: 登录结果
    '''
    conn = GetConn()
    cursor = conn.cursor()
    sql = "select * from user where user_name=%s and pass_word=%s"
    res = cursor.execute(sql, [data['user_name'], GetMd5(data['pass_word'])])
    ret = cursor.fetchone()
    if res == 0:
        js = {"code": -1, "data": "", "msg": "账号或密码不正确"}
        return js
    js = {"code": 0, "data": ret, "msg": "登录成功"}

    return js


def Register(data):
    '''
    用户注册
    :param data: 用户数据
    :return: 注册结果
    '''
    conn = GetConn()
    cursor = conn.cursor()

    sql = "select * from user where user_name=%s"
    res = cursor.execute(sql, [data['user_name']])
    if res == 1:
        js = {"code": -1, "data": "", "msg": "该账号已经注册"}
        return js

    sql = "insert into user(user_name,pass_word,token) values(%s,%s,%s)"
    token = str(uuid.uuid1()).replace("-", "")
    res = cursor.execute(sql, [data['user_name'], GetMd5(data['pass_word']), token])
    print(res)
    if res == 0:
        js = {"code": -1, "data": "", "msg": "注册失败"}
        return js
    ret = data
    ret['token'] = token
    js = {"code": 0, "data": ret, "msg": "注册成功"}

    return js

def GetUserByToken(token):
    '''
    根据token获取用户id
    :param token:
    :return:
    '''
    conn = GetConn()
    cursor = conn.cursor()
    sql = "select * from user where token = %s"
    res = cursor.execute(sql, [token])
    ret = cursor.fetchone()
    if res == 0:
        return -1
    return ret


